import  asyncRoutes  from '@/router/asyncRoutes.js'
import constantRoutes from '@/router/constroutes.js'
import axios from "axios";
import Cookies from 'js-cookie'
const TokenKey = 'zyr-Token'
const state={
  test:11,
  token:Cookies.get(TokenKey),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  accessedRoutes:[],//新增的动态路由
  routes: [],//当前roles所有路由
}
const mutations={
  settoken(state,token){
    state.token=token
  },
  SET_ROLES(state,roles){
    state.roles=roles
  },
  SET_NAME(state,name){
    state.name=name
  },
  SET_AVATAR(state,avatar){
    state.avatar=avatar
  },
  SET_INTRODUCTION(state,introduction){
    state.introduction=introduction
  },
  SET_ROUTES(state,accessedRoutes){
    state.accessedRoutes=accessedRoutes
    state.routes=accessedRoutes.concat(constantRoutes)
  }
}
const actions={
  // {commit}解构赋值context
  login({commit},userinfo){
    return new Promise((resove,reject)=>{
      axios.post('/user/login',userinfo).then(res=>{
        let token='admin-token'  //token由res解构得到，此处模拟   
        commit('settoken',token)
        Cookies.set(TokenKey,token)
        resove(res)
      }).catch(error=>{
        reject(error)
      })
    })
  },
  getInfo({commit,state}){
    return new Promise((resolve,reject)=>{
      axios.get(`/user/info`,{token:state.token}).then(res=>{
        let moniData={//模拟数据
          avatar: "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
          introduction: "I am a super administrator",
          name: "Super Admin",
          roles: ["admin"]
        }
        const { roles, name, avatar, introduction }=moniData
        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        // 动态路由数据
        let accessedRoutes=[]
        let roles1='editor'//此处现在把角色写成唯一根据项目需求来
        if (roles1=='admin') {
          accessedRoutes = asyncRoutes || []
        } else {
          accessedRoutes = filterAsyncRoutes(asyncRoutes, roles1)
        }
        commit('SET_ROUTES', accessedRoutes)
        console.log(accessedRoutes,roles1);       
        resolve(accessedRoutes)
      }).catch((error)=>{
        reject(error)       
      })
    })
  },
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      Cookies.remove(TokenKey)
      resolve()
    })
  },
}
//动态筛选路由算法
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
      // return roles.some(role => route.meta.roles.includes(role))
      return route.meta.roles.includes(roles)
  } else {
      return true
  }
}
function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route=>{
      const tmp = { ...route }
      if (hasPermission(roles, tmp)) {
          if (tmp.children) {
              tmp.children = filterAsyncRoutes(tmp.children, roles)
          }
          res.push(tmp)
      }
  })
  return res
}
export default {state,mutations,actions}